﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using ThoiTrang.Business;
using ThoiTrang.Entities;
using ThoiTrang.Data;
using System.Text;
using System.Collections.Generic;
using System.IO;

public partial class Admin_adm_cat : System.Web.UI.Page
{
    public string _maintable = "";
    private ThoiTrang.Business.a_CatGroupService _bCatGroup=new a_CatGroupService();

    #region "Page functions"
    private void _BindDropdownGroup()
    {
        this.drpGroup.DataSource = a_CatGroupService.Geta_CatGroupList(a_CatGroupColumns.UGroupName, OrderDirection.ASC);
        this.drpGroup.DataTextField = a_CatGroupColumns.UGroupName.ToString();
        this.drpGroup.DataValueField = a_CatGroupColumns.GroupID.ToString();
        this.drpGroup.DataBind();
    }

    private void _BindGreeting()
    {
        a_User au=a_UserService.Geta_User(Request.Params["ckid"]);
        if (au != null)
        {
            this.lblGretting.Text = "Hi " + au.Firstname + " " + au.Lastname;
        }
    }

    private void _ReadParam()
    {
        try
        {
            if (Request.Params["catid"] != null && Request.Params["isedit"] != null)
            {
                a_CatMain aCm = a_CatMainService.Geta_CatMain(int.Parse(Request.Params["catid"]));
                if (aCm != null)
                {
                    this.txtNameEN.Text = aCm.Name;
                    this.txtNameVN.Text = aCm.UName;
                }
                this.btnUpdateCategory.Visible = true;
            }
            else if (Request.Params["catid"] != null && Request.Params["isdel"] == "1")
            {
                //Kiem tra xem co sub cat khong
                Int32 cid = Int32.Parse(Request.Params["catid"]);
                Int32 noSubcat = a_CatSubService.Geta_CatSubListByCatMain(cid).Count;
                if (noSubcat > 0)
                {
                    //Khong duoc xoa
                    this.lblAlert.Text = "You must delete sub categories first";
                    this.lblAlert.Visible = true;
                }
                else
                {
                    //Xoa du main cat
                    a_CatMainService.Deletea_CatMain(cid);
                    this.lblAlert.Text = "Delete category sucessfully";
                    this.lblAlert.Visible = true;
                }
            }
            else if (Request.Params["catid"]!=null && Request.Params["subcatid"] != null && Request.Params["isremove"] == "1" && Request.Params["issub"] == "1")
            {
                Int32 cid = Int32.Parse(Request.Params["catid"]);
                Int32 sid = Int32.Parse(Request.Params["subcatid"]);
                a_CatTree act = a_CatTreeService.Geta_CatTree_mcid_scid(cid, sid);
                if (act != null)
                {
                    a_CatTreeService.Deletea_CatTree(act.ID);
                    this.lblAlert.Text = "Sub category has sucessfully removed";
                    this.lblAlert.Visible = true;
                }
            }
            else if (Request.Params["subcatid"] != null && Request.Params["isdel"] != null && Request.Params["issub"]!=null)
            {
                Int32 sid = Int32.Parse(Request.Params["subcatid"]);
                a_CatSub acs = a_CatSubService.Geta_CatSub(sid);
                if (acs != null)
                {
                    a_CatSubService.Deletea_CatSub(acs.SubCatID);
                    this.lblAlert.Text = "Sub category has sucessfully deleted";
                    this.lblAlert.Visible = true;
                }
            }
            else if (Request.Params["subcatid"] != null && Request.Params["isedit"] != null)
            {
                this.btnUpdateSubcategory.Visible = true;
                Int32 sid = Int32.Parse(Request.Params["subcatid"]);
                a_CatSub acs = a_CatSubService.Geta_CatSub(sid);
                if (acs != null)
                {
                    this.txtSubnameEN.Text = acs.Name;
                    this.txtSubnameVN.Text = acs.UName;
                    this.txtCatOrdering.Text = acs.Ordering.ToString();
                }
            }
            else
            {
                this.btnUpdateCategory.Visible = false;
            }
        }
        catch (Exception ex)
        {
            //throw new exception here
        }
    }

    private void _BindRepeaterSubcat()
    {
        this.rptSubCat.DataSource = a_CatSubService.Geta_CatSubList(a_CatSubColumns.UName, OrderDirection.ASC);
        this.rptSubCat.DataBind();
    }

    #region "Create HTML Content"
    private string _CreateGroupContent(bool addsubcat)
    {
        StringBuilder sb = new StringBuilder();
        foreach (a_CatGroup aCGItem in a_CatGroupService.Geta_CatGroupList(a_CatGroupColumns.UGroupName, OrderDirection.ASC))
        {
            sb.Append("<tr><td colspan='2' style='height:1px;background-color:Gray'></td></tr>");
            sb.Append("<tr>");
            sb.Append("<td class='title'style='padding-left:10px; color:#947300; font-weight:bold;'>" + aCGItem.UGroupName + " <em>(" + this._GetNoArticleGroup(aCGItem.GroupID).ToString() + ")</em></td>");
            sb.Append("<td></td>");
            sb.Append("</tr>");
            sb.Append(this._CreateMainCategoryContent(aCGItem.GroupID,addsubcat));
        }
        return sb.ToString();
    }

    private string _CreateMainCategoryContent(Int32 gId,bool addsubcat)
    {
        StringBuilder sb = new StringBuilder();
        foreach (a_CatMain aMCItem in a_CatMainService.Geta_CatMainListByGroup(gId))
        {
            sb.Append("<tr><td colspan='2' style='height:1px;background-color:Gray'></td></tr>");
            if (Request.Params["catid"] != null)
            {
                if (int.Parse(Request.Params["catid"]) == aMCItem.CatID)
                {
                    sb.Append("<tr bgcolor='#9f8d92'>");
                }
            }
            else
            {
                sb.Append("<tr>");
            }
            sb.Append("<td class='lstitle'>" + _CreateMainCatLink(aMCItem.CatID) + aMCItem.UName + "</a> <em>(" + this._GetNoArticleMCategory(aMCItem.CatID).ToString() + ")</em></td>");
            sb.Append("<td>" + _CreateEditMainCatLink(aMCItem.CatID) + "</td>");
            sb.Append("</tr>");
            if (Request.Params["catid"] != null && Request.Params["isedit"]==null)
            {
                Int32 mcid = Int32.Parse(Request.Params["catid"].ToString());
                if (mcid == aMCItem.CatID)
                {
                    sb.Append(this._CreateSubCategoryContent(mcid));
                }
            }
            else if (addsubcat)
            {
                sb.Append(this._CreateSubCategoryContent(aMCItem.CatID));
            }
        }

        return sb.ToString();
    }

    private string _CreateSubCategoryContent(Int32 mId)
    {
        StringBuilder sb = new StringBuilder();
        foreach (a_CatTree act in a_CatTreeService.Geta_CatTreeList_mcid(mId,a_CatTreeColumns.SubCatID,OrderDirection.ASC))
        {
            a_CatSub aSCItem = a_CatSubService.Geta_CatSub(act.SubCatID);
            if (aSCItem != null)
            {
                sb.Append("<tr><td colspan='2' style='height:1px;background-color:Gray'></td></tr>");
                sb.Append("<tr>");
                sb.Append("<td class='nstitle' style='padding-left:30px;color:#444;'>" + aSCItem.Ordering.ToString() + ". " + aSCItem.UName + " <em>(" + this._GetNoArticleSCategory(mId, aSCItem.SubCatID).ToString() + ")</em></td>");
                sb.Append("<td width=\"70\">" + this._CreateEditSubCatLink(aSCItem.SubCatID, mId) + "</td>");
                sb.Append("</tr>");
            }
        }
        return sb.ToString();
    }

    private string _CreateEditMainCatLink(Int32 mId)
    {
        if (Request.Params["ckid"] != null)
        {
            return "<a href='adm_cat.aspx?ckid=" + Request.Params["ckid"].ToString() + "&catid=" + mId.ToString() + "&isedit=1'><img src='../images/ico_edit.gif' alt='edit' width='12' height='12' /></a><a href='adm_cat.aspx?ckid=" + Request.Params["ckid"].ToString() + "&catid=" + mId.ToString() + "&isdel=1&iscat=1' onclick="+"\""+"return confirm('Do you want to DELETE?')"+"\""+"'><img src='../images/ico_delete.gif' alt='del' width='16' height='13' /></a>";
        }
        else
        {
            return "<a href='adm_cat.aspx?catid=" + mId.ToString() + "&isedit=1'><img src='../images/ico_edit.gif' alt='edit' width='12' height='12' /></a><a href='adm_cat.aspx?catid=" + mId.ToString() + "&isdel=1&iscat=1'><img src='../images/ico_delete.gif' alt='del' width='16' height='13' /></a>";
        }
    }

    private string _CreateMainCatLink(Int32 mId)
    {
        if (Request.Params["ckid"] != null)
        {
            return "<a class='clsMain' href='adm_cat.aspx?ckid=" + Request.Params["ckid"].ToString() + "&catid=" + mId.ToString() + "'>";
        }
        else
        {
            return "<a class='clsMain' href='adm_cat.aspx?catid=" + mId.ToString() + "'>";
        }
    }

    private string _CreateEditSubCatLink(Int32 sId,Int32 mId)
    {
        a_CatTree act = a_CatTreeService.Geta_CatTree_mcid_scid(mId, sId);
        if (act != null)
        {
            if (Request.Params["ckid"] != null)
            {
                return "<a href='adm_cat.aspx?ckid=" + Request.Params["ckid"].ToString() + "&catid=" + mId.ToString() + "#' onclick=" + "\"window.open('adm_subcat_edit.aspx?ckid=" + Request.Params["ckid"] + "&ctid=" + act.ID.ToString() + "&scn=" + System.Web.HttpUtility.HtmlEncode(a_CatSubService.Geta_CatSub(act.SubCatID).UName) + "','mywindow','menubar=0,resizeable=0,width=400,height=250')" + "\"" + "><img src='../images/ico_move.gif' alt='edit' width='12' height='12' /></a><a onclick=" + "\"" + "return confirm('Are you sure want to remove?')" + "\"" + "' href='adm_cat.aspx?ckid=" + Request.Params["ckid"].ToString() + "&subcatid=" + sId.ToString() + "&isremove=1" + "&ctid=" + act.ID.ToString() + "&catid=" + mId.ToString() + "&issub=1'><img src='../images/ico_cancel.gif' alt='del' width='16' height='13' /></a><img src='images/icon_google.jpg' height='12' onclick=\"window.open('adm_seo_content.aspx?scid=" + a_CatSubService.Geta_CatSub(act.SubCatID).SubCatID.ToString() + "&ckid=" + SessionManager.GetCookie() + "','mywindow','menubar=0,resizeable=0,width=670,height=570');\" style=\"cursor:pointer;\" />";
            }
            else
            {
                return "<a href='adm_cat.aspx?catid=" + mId.ToString() + "#' onclick=" + "\"window.open('adm_subcat_edit.aspx?ctid=" + act.ID.ToString() + "&scn=" + System.Web.HttpUtility.HtmlEncode(a_CatSubService.Geta_CatSub(act.SubCatID).UName) + "','mywindow','menubar=0,resizeable=0,width=400,height=250')" + "\"" + "><img src='../images/ico_move.gif' alt='edit' width='12' height='12' /></a><a href='adm_cat.aspx?subcatid=" + sId.ToString() + "&isremove=1" + "&ctid=" + act.ID.ToString() + "&catid=" + mId.ToString() + "&issub=1'><img src='../images/ico_cancel.gif' alt='del' width='16' height='13' /></a><img src='images/icon_google.jpg' height='12' onclick=\"window.open('adm_seo_content.aspx?scid=" + a_CatSubService.Geta_CatSub(act.SubCatID).SubCatID.ToString() + "','mywindow','menubar=0,resizeable=0,width=670,height=570');\" style=\"cursor:pointer;\" />";
            }
        }
        else
        {
            return "";
        }
        
    }

    public string _CreateEditSubcategoryRepeater(Int32 sId)
    {
        if (Request.Params["ckid"] != null)
        {
            return "<a href='adm_cat.aspx?ckid=" + Request.Params["ckid"].ToString() + "&subcatid=" + sId.ToString() + "&isedit=1'><img src='../images/ico_edit.gif' alt='edit' width='12' height='12' /></a><a onclick=" + "\"" + "return confirm('Are you sure want to delete?')" + "\"" + "' href='adm_cat.aspx?ckid=" + Request.Params["ckid"].ToString() + "&subcatid=" + sId.ToString() + "&isdel=1" + "&issub=1'><img src='../images/ico_delete.gif' alt='del' width='16' height='13' /></a>";
        }
        else
        {
            return "<a href='adm_cat.aspx?subcatid=" + sId.ToString() + "&isedit=1'><img src='../images/ico_edit.gif' alt='edit' width='12' height='12' /></a><a href='adm_cat.aspx?subcatid=" + sId.ToString() + "&isdel=1" + "&issub=1'><img src='../images/ico_delete.gif' alt='del' width='16' height='13' /></a>";
        }
    }

    #endregion

    #region "Count Articles"
    private Int32 _GetNoArticleGroup(int gId)
    {
        Int32 totalArticles = 0;
        foreach (a_CatMain mc in a_CatMainService.Geta_CatMainListByGroup(gId))
        {
            totalArticles += this._GetNoArticleMCategory(mc.CatID);
        }
        return totalArticles;
    }

    private Int32 _GetNoArticleMCategory(int MCId)
    {
        Int32 totalArticles = 0;
        foreach (a_CatSub sc in a_CatSubService.Geta_CatSubListByCatMain(MCId))
        {
            totalArticles += this._GetNoArticleSCategory(MCId, sc.SubCatID);
        }
        return totalArticles;
    }

    private Int32 _GetNoArticleSCategory(int MCId, int SCId)
    {
        Int32 total = 0;
        a_ArticleService.Geta_ArticleListBySubIdAndMainId(MCId, SCId, a_ArticleColumns.ID, OrderDirection.ASC, 1, 100000, out total);
        return total;
    }
    #endregion

    #endregion

    #region "Event"
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            
            this._BindDropdownGroup();
            this._ReadParam();
            this._BindRepeaterSubcat();
            this._maintable= _CreateGroupContent(false);
            this.lblMemory.Text = this._maintable;
            this._BindGreeting();
        }

        //if (SessionManager.IsLogged)
        //{
        //    Response.Write(SessionManager.GetCookie());
        //}
    }

    protected void btnAddCategory_Click(object sender, EventArgs e)
    {
        try
        {
            a_CatMain acm = new a_CatMain();
            acm.GroupID = int.Parse(this.drpGroup.SelectedValue);
            acm.Name = this.txtNameEN.Text;
            acm.UName = this.txtNameVN.Text;
            a_CatMainService.Createa_CatMain(acm);
            this._maintable = _CreateGroupContent(false);
            this.lblAlert.Text = "Add main category sucessfully";
            this.lblAlert.Visible = true;
        }
        catch (Exception ex)
        {
            //throw exception to error page
        }
    }

    protected void btnUpdateCategory_Click(object sender, EventArgs e)
    {
        try
        {
            if (Request.Params["catid"] != null)
            {
                a_CatMain acm = a_CatMainService.Geta_CatMain(int.Parse(Request.Params["catid"]));
                acm.GroupID = int.Parse(this.drpGroup.SelectedValue);
                acm.Name = this.txtNameEN.Text;
                acm.UName = this.txtNameVN.Text;
                a_CatMainService.Updatea_CatMain(acm);
                this._maintable = _CreateGroupContent(false);
                this.lblAlert.Text = "Update main category sucessfully";
                this.lblAlert.Visible = true;
            }
        }
        catch (Exception ex)
        {
            //throw exception to error page
        }
    }

    protected void btnExpandAll_Click(object sender, EventArgs e)
    {
        this._maintable = this._CreateGroupContent(true);
    }

    protected void btnCollapseAll_Click(object sender, EventArgs e)
    {
        this._maintable = this._CreateGroupContent(false);
    }

    protected void btnAddSubCategory_Click(object sender, EventArgs e)
    {
        try
        {
            a_CatSub acs = new a_CatSub();
            acs.Name = this.txtSubnameEN.Text;
            acs.UName = this.txtSubnameVN.Text;
            acs.Ordering = int.Parse(this.txtCatOrdering.Text);
            if (Request.Params["catid"] != null)
            {
                acs.MainCatID = int.Parse(Request.Params["catid"]);
                a_CatSubService.Createa_CatSub(acs);
                a_CatTree act = new a_CatTree();
                act.CatID = acs.MainCatID;
                act.SubCatID = acs.SubCatID;
                a_CatTreeService.Createa_CatTree(act);
            }
            else
            {
                a_CatSubService.Createa_CatSub(acs);
            }

            this._maintable = this.lblMemory.Text;
            this._BindRepeaterSubcat();
            this.lblAlert.Text = "Add sub category sucessfully";
            this.lblAlert.Visible = true;
        }
        catch (Exception ex)
        {
            //throw exception to error page
        }
    }

    protected void btnUpdateSubcategory_Click(object sender, EventArgs e)
    {
        try
        {
            if (Request.Params["subcatid"] != null)
            {
                a_CatSub acs = a_CatSubService.Geta_CatSub(int.Parse(Request.Params["subcatid"]));
                acs.Name = this.txtSubnameEN.Text;
                acs.UName = this.txtSubnameVN.Text;
                acs.Ordering = int.Parse(this.txtCatOrdering.Text);
                a_CatSubService.Updatea_CatSub(acs);
                this._BindRepeaterSubcat();
                this._maintable = this.lblMemory.Text;
                this.lblAlert.Text = "Update sub category sucessfully";
                this.lblAlert.Visible = true;
                this.GenerateMenu();
            }
        }
        catch (Exception ex)
        {
            //throw exception to error page
        }
    }

    protected void GenerateMenu()
    {
        string codeStr = string.Empty;
        foreach (a_CatGroup acg in a_CatGroupService.Geta_CatGroupList(a_CatGroupColumns.GroupID,OrderDirection.ASC))
        {
            codeStr = "";
            List<a_CatMain> catMains = a_CatMainService.Geta_CatMainListByGroup(acg.GroupID);
            foreach (a_CatMain catMain in catMains)
            {
                List<a_CatSub> catSubs = a_CatSubService.Geta_CatSubList_join_cattree(catMain.CatID);
                bool isShowAllMain = false;

                for (int i = 0; i < catSubs.Count; i++)
                {
                    if (catSubs[i].Ordering != 0)
                    {
                        isShowAllMain = true;
                        break;
                    }
                }
                if (isShowAllMain)
                {
                    codeStr += String.Format("\t\t\t\t<p class=\"cat\">{0}</p>", catMain.UName);
                    codeStr += "\t\t\t\t<ul class=\"category\">";
                    //Kiem tra all subcat


                    for (int i = 0; i < catSubs.Count; i++)
                    {
                        if (catSubs[i].Ordering > 0 && catSubs[i].Ordering != null)
                        {
                            string link = ResolveUrl(TTHelper.GetDetailLink(catMain, catSubs[i]));
                            if (i % 2 == 0)
                                codeStr += String.Format("\t\t\t\t\t<li><a href=\"{0}\">{1}</a></li>", link, catSubs[i].UName);
                            else
                                codeStr += String.Format("\t\t\t\t\t<li class=\"se\"><a href=\"{0}\">{1}</a></li>", link, catSubs[i].UName);
                        }
                    }
                    codeStr += "\t\t\t\t</ul>";
                }
            }
            //Gen code for Files
            string sFile = acg.GroupName.Replace(" ", "");
            File.WriteAllText(Server.MapPath("~/Files/"+sFile+".txt"), codeStr);

        }
    }

    protected void btnAddToMainCategories_Click(object sender, EventArgs e)
    {
        try
        {
            if (Request.Params["catid"] != null)
            {
                int cid = int.Parse(Request.Params["catid"]);
                foreach (RepeaterItem rpi in this.rptSubCat.Items)
                {
                    Label lblId = (Label)rpi.FindControl("lblId");
                    CheckBox chk = (CheckBox)rpi.FindControl("chkCheck");
                    if (chk != null && chk.Checked)
                    {
                        //Thuc hien move sang main
                        a_CatSub acs = a_CatSubService.Geta_CatSub(int.Parse(lblId.Text));
                        acs.MainCatID = cid;
                        a_CatSubService.Updatea_CatSub(acs);
                        //Xoa cattree o trang cu
                        foreach (a_CatTree actDel in a_CatTreeService.Geta_CatTreeList_scid(int.Parse(lblId.Text), a_CatTreeColumns.CatID, OrderDirection.ASC))
                        {
                            a_CatTreeService.Deletea_CatTree(actDel.ID);
                        }
                        //Them vao tree
                        a_CatTree act = new a_CatTree();
                        act.CatID = cid;
                        act.SubCatID = acs.SubCatID;
                        a_CatTreeService.Createa_CatTree(act);
                    }
                }
                //Thoong bao thanh cong
                this.lblAlert.Text = "Move to main category sucessfully";
                this.lblAlert.Visible = true;
                this._maintable = this._CreateGroupContent(false);
            }
            else
            {
                this.lblAlert.Text = "You must choose main category to move";
                this.lblAlert.Visible = true;
                this._maintable = this.lblMemory.Text;
            }
        }
        catch (Exception ex)
        {
            //throw new exception
        }
    }

    protected void btnUpdateOrder_Click(object sender, EventArgs e)
    {
        this.GenerateMenu();
        this._maintable = _CreateGroupContent(false);
        CommonFunc.ShowAlertMessage(this.lblAlert, "Sucessfully re-ordered!");
    }
    #endregion 

    
}
